// 加载Express模块
<<<<<<< HEAD
const express = require('express');
// 加载MySQL模块
const mysql = require('mysql');
// 加载bodyParser模块
const bodyParser = require('body-parser');
// 创建MySQL连接池
const pool = mysql.createPool({
  host: '127.0.0.1',   //MySQL服务器地址
  port: 3306,          //MySQL服务器端口号
  user: 'root',        //数据库用户的用户名
  password: '',        //数据库用户密码
  database: 'nx',    //数据库名称
  connectionLimit: 20, //最大连接数
  charset: 'utf8'      //数据库服务器的编码方式
});
// 创建服务器对象
const server = express();
server.use(bodyParser.urlencoded({
  extended: false
}));
// 加载CORS模块
const cors = require('cors');
// 使用CORS中间件
server.use(cors({
  origin: ['http://localhost:8080', 'http://127.0.0.1:8080']
}));
=======
const express = require("express")
// 加载MySQL模块
const mysql = require("mysql")
// 加载bodyParser模块
const bodyParser = require("body-parser")
const fs = require('fs');
// 创建MySQL连接池
const pool = mysql.createPool({
  host: "127.0.0.1", //MySQL服务器地址
  port: 3306, //MySQL服务器端口号
  user: "root", //数据库用户的用户名
  password: "", //数据库用户密码
  database: "nx", //数据库名称
  connectionLimit: 20, //最大连接数
  charset: "utf8", //数据库服务器的编码方式
})
var avatar="";
// 创建服务器对象
const server = express()
server.use(
  bodyParser.urlencoded({
    extended: false,
  })
)

//托管静态资源
server.use(express.static('./public'))

// 加载CORS模块
const cors = require("cors")
// 使用CORS中间件
server.use(
  cors({
    origin: ["http://localhost:8080", "http://127.0.0.1:8080"],
  })
)

// 获取礼品卡列表数据
server.get("/giftcard", (req, res) => {
  // 获取地址栏中的id数据
  // SQL查询
  let text = req.query.items
  console.log(text)
  let sql = `select * from nx_giftcard`
  // 执行SQL查询
  pool.query(sql, text, (error, data) => {
    if (error) throw error
    // 返回数据到客户端
    console.log(data)
    res.send({ message: "ok", code: 200, data: data })
  })
})
// 获取积分商城分类
server.get("/category", (req, res) => {
  // 获取地址栏中的id数据
  // SQL查询
  let text = req.query.items
  console.log(text)
  let sql = `select DISTINCT title from nx_integral`
  // 执行SQL查询
  pool.query(sql, text, (error, data) => {
    if (error) throw error
    // 返回数据到客户端
    console.log(data)
    res.send({ message: "ok", code: 200, data: data })
  })
})
// 获取积分商城中的所有数据
server.get("/integral", (req, res) => {
  // 获取地址栏中的id数据
  // SQL查询
  let text = req.query
  console.log(text)
  let sql = "select * from nx_integral"
  // 执行SQL查询
  pool.query(sql, (error, data) => {
    if (error) throw error
    // 返回数据到客户端
    console.log(data)
    res.send({ message: "ok", code: 200, data: data })
  })
})
// 获取积分商城具体数据
server.get("/integral/:id", (req, res) => {
  // 获取地址栏中的id数据
  // SQL查询
  let id = req.params.id
  console.log(id)
  let sql = `select * from nx_integral where id=?`
  // 执行SQL查询
  pool.query(sql, [id], (error, data) => {
    if (error) throw error
    // 返回数据到客户端
    console.log(data)
    res.send({ message: "ok", code: 200, data: data })
  })
})
// 获取积分商城各分类中的数据
server.get("/classify", (req, res) => {
  // 获取地址栏中的id数据
  // SQL查询
  let text = req.query.title
  console.log(text)
      console.log("积分商城：", this.classify)
     // select DISTINCT title from nx_integral
  let sql = `select * from nx_integral where title=?;`
  // 执行SQL查询
  pool.query(sql, text, (error, data) => {
    if (error) throw error
    // 返回数据到客户端
    console.log(data)
    res.send({ message: "ok", code: 200, data: data })
  })
})

>>>>>>> da85937c46a68704623e1c653d56a4a2c6859127

//获取商品列表项
server.get('/product', (req, res) => {
  //获取地址栏中的id参数
  // SQL查询
  let sql=" select distinct text from nx_product"
  // let sql = "SELECT * FROM nx_product ";
  // 执行SQL查询
  pool.query(sql, (error, data) => {
    if (error) throw error;
    // 返回数据到客户端
    console.log(data)
    res.send({ message: 'ok', code: 200, data: data });
  })
});
//获取商品列表对应数据
server.get('/type', (req, res) => {
  //获取地址栏中的id参数
  // SQL查询
  let text=req.query.items
  console.log(text)
  let sql=" select * from nx_product where text=?"
  // 执行SQL查询
  pool.query(sql,text, (error, data) => {
    if (error) throw error;
    // 返回数据到客户端
    console.log(data)
    res.send({ message: 'ok', code: 200, data: data });
  })
});
<<<<<<< HEAD
//获取商品详情
server.get('/list', (req, res) => {
  //获取地址栏中的id参数
  // SQL查询
  let did=req.query.did
  console.log(did)
  let sql=" select * from nx_product where did=?"
  // 执行SQL查询
  pool.query(sql,did, (error, data) => {
    if (error) throw error;
    // 返回数据到客户端
    console.log(data)
    res.send({ message: 'ok', code: 200, data: data });
  })
});
=======
>>>>>>> da85937c46a68704623e1c653d56a4a2c6859127
//获取搜索对应数据
server.get('/search', (req, res) => {
  //获取地址栏中的id参数
  // SQL查询
  let text=req.query.items
  console.log(text)
  let sql=`select * from nx_product where title like '%${text}%'`
  // 执行SQL查询
  pool.query(sql,text, (error, data) => {
    if (error) throw error;
    // 返回数据到客户端
    console.log(data)
    res.send({ message: 'ok', code: 200, data: data });
  })
});


<<<<<<< HEAD
=======
//用户注册接口
server.post('/register', (req, res) => {
  console.log(req.body)
  //console.log(md5('123456'));
  // 获取用户名和密码信息
  let uname = req.body.uname;
  let pwd = req.body.pwd;
  let phone = req.body.phone;
  let tname = req.body.tname;
  let birthday = req.body.selectTime;
  if(!avatar){
    avatar="public/avatar/0.jpg"
  }
  //以uid为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(uid) AS count FROM USERLIST WHERE uname=?';
  pool.query(sql, [uname], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      let sql = 'INSERT INTO userlist(uname,pwd,phone,tname,birthday,img) VALUES(?,?,?,?,?,?)';
      pool.query(sql, [uname, pwd,phone,tname,birthday,avatar], (error, results) => {
        if (error) throw error;
        
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: 'user exists', code: 201 });
   }
  });
});


// 用户登录接口
server.post('/login', (req, res) => {
  //获取用户名和密码信息
  let uname = req.body.uname;
  let pwd = req.body.pwd;
  // SQL语句
  let sql = 'SELECT * FROM userlist WHERE uname=? AND pwd=?';
  pool.query(sql, [uname, pwd], (error, results) => {
    if (error) throw error;
    if(results.length == 0){ //登录失败
      res.send({message:'login failed',code:201})
    } else {                 //登录成功
      res.send({message:'ok',code:200,result:results[0]})
    }
  })
});

//图片上传接口
server.post('/upavatar', (req, res, next)=> {
  let imgData = req.body.data
  let base64 = imgData.replace(/\s/g, "+")
  let base64Data = base64.replace(/^data:image\/\w+;base64,/,"")
  let dataBuffer=Buffer.from(base64Data, 'base64')
  let imgtype =req.body.imgtype
  let imgname=Math.floor(Math.random()*100)
  fs.writeFile(`public/avatar/${imgname}.${imgtype}`, dataBuffer, function (err){
    if (err){ console.log(err)}else{
      avatar=`${imgname}.${imgtype}`
      // let sql=`update userlist set avatar="${imgname}.${imgtype}" where u_id="${imgname}"`
      // pool.query(sql, (err, result)=>{
      //   if (err) {
      //     next(err)
      //     return
      //   }
      // })
    }
  })
  return res.send({
    "code":200,  
    "msg":"success",
    'avatarname':`${imgname}.${imgtype}`
 })
})


//图片修改接口
server.post('/img', (req, res, next)=> {
  let imgData = req.body.data
  let base64 = imgData.replace(/\s/g, "+")
  let base64Data = base64.replace(/^data:image\/\w+;base64,/,"")
  let dataBuffer=Buffer.from(base64Data, 'base64')
  let imgtype =req.body.imgtype
  let imgname=req.body.uname
  fs.writeFile(`public/avatar/${imgname}.${imgtype}`, dataBuffer, function (err){
    if (err){ console.log(err)}else{
      avatar=`${imgname}.${imgtype}`
      let sql=`update userlist set img="${imgname}.${imgtype}" where uname="${imgname}"`
      pool.query(sql, (err, result)=>{
        if (err) {
          next(err)
          return
        }
      })
    }
  })
  return res.send({
    "code":200,  
    "msg":"success",
    'avatarname':`${imgname}.${imgtype}`
 })
})


//用户修改个人信息
server.post('/update', (req, res, next) => {
  let obj = req.body
  console.log(obj.uname); 
      let sql = `update userlist set uname="${obj.uname}",pwd="${obj.upwd}",tname="${obj.tname}",phone="${obj.phone}",birthday="${obj.birthday}" where uid="${obj.uid}";`
      pool.query(sql, (err, data) => {
          if (err) {
            next(err)
            return
          }
          if (data.affectedRows !== 0) {
            res.send({
              "code": 200,
              "msg": "修改成功"
          })          
      } else {
          res.send({
              "code": 401,
              "msg": "修改失败"
          })
      }
  }) 
})


// 获取用户信息数据的接口
server.get('/getinfo', (req, res) => {
  let uname=req.query.uname
  // SQL查询
  let sql = "SELECT * FROM userlist WHERE uname=?";

  // 执行SQL查询
  pool.query(sql,uname,(error, results) => {
    if (error) throw error;
    // 返回数据到客户端
    res.send({ message: 'ok', code: 200, result: results});
  })
})


//用户收货地址接口
server.post('/adress', (req, res) => {
  console.log(req.body)
  // 获取用户名信息
  let name = req.body.name;
  let phone = req.body.phone;
  let area = req.body.area;
  let areadetail = req.body.selectTime;
  if(!avatar){
    avatar="public/avatar/0.jpg"
  }
  //以uid为条件进行查找操作，以保证用户名的唯一性
  let sql = 'SELECT COUNT(uid) AS count FROM USERLIST WHERE uname=?';
  pool.query(sql, [uname], (error, results) => {
    if (error) throw error;
    let count = results[0].count;
    if (count == 0) {
      // 将用户的相关信息插入到数据表
      let sql = 'INSERT INTO userlist(uname,pwd,phone,tname,birthday,img) VALUES(?,?,?,?,?,?)';
      pool.query(sql, [uname, pwd,phone,tname,birthday,avatar], (error, results) => {
        if (error) throw error;
        
        res.send({ message: 'ok', code: 200 });
      })
    } else {
      res.send({ message: 'user exists', code: 201 });
   }
  });
});

>>>>>>> da85937c46a68704623e1c653d56a4a2c6859127


// 指定服务器对象监听的端口号
server.listen(3000, () => {
  console.log('server is running...');
});